package com.shuhe.thread;

import com.shuhe.metastore.DBSql;
import com.shuhe.metastore.MetaMysql;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;

import static com.shuhe.common.CommonFunction.closeDb;

public class DbExecThread implements Runnable {
    private ArrayList<String> execs;

    private static Logger logger = Logger.getLogger(DbExecThread.class);

    public DbExecThread(ArrayList<String> execs) {
        this.execs = execs;
    }

    public void run() {
        Connection dbConn = null;
        Connection metaConn = null;
        try {
            long beginTime = Calendar.getInstance().getTimeInMillis();
            metaConn = MetaMysql.connect();
            String sql = "select * from mxgc_exec_sql_config where type = '" + DBSql.dbType + "'";
            ResultSet rs = MetaMysql.querySql(metaConn, sql);
            String query = "";
            if (rs.next()) {
                query = rs.getString("query");
            }
            dbConn = DBSql.connect();
            ArrayList<String> sqls = new ArrayList<>();
            if (query.length() > 0) {
                rs = DBSql.querySql(dbConn, query);
                while (rs.next()) {
                    sql = rs.getString("query");
                    sqls.add(sql);
                }
            }
            for (int i = 0; i < execs.size(); i++) {
                sql = execs.get(i);
                for (int j = 0; j < sqls.size(); j++) {
                    if (sql.startsWith(sqls.get(j))) {
                        logger.info("DbExecThread: run sql:" + sql);
                        return;
                    }
                }
            }

            for (int i = 0; i < execs.size(); i++) {
                try {
                    DBSql.execSql(dbConn, execs.get(i));
                } catch (Exception ex) {
                    logger.info(ex.getMessage());
                }
            }
            long endTime = Calendar.getInstance().getTimeInMillis();

            logger.info("DbExecThread:" + (endTime - beginTime));
        } catch (Exception ex) {
            logger.info(ex.getMessage());
        } finally {
            closeDb(metaConn);
            closeDb(dbConn);
        }
    }
}
